import React, { useState, useEffect, useRef } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import {
  Container,
  Tabs,
  Tab,
  Box,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  TextField,
  Button,
  Select,
  MenuItem,
  Checkbox,
  Typography,
  InputLabel,
} from "@mui/material";

const options2 = [
  { value: "1", label: "音视频质量不变" },
  { value: "2", label: "WEB视频流媒体" },
  { value: "3", label: "H264压缩" },
  { value: "4", label: "H264压缩-Intel加速" },
  { value: "5", label: "H264压缩-AMD加速" },
  { value: "6", label: "H264压缩-NV加速" },
  { value: "7", label: "H265压缩" },
  { value: "8", label: "H265压缩-AMD加速" },
  { value: "9", label: "H265压缩-AMD加速" },
  { value: "10", label: "H265压缩-NV加速" },
  { value: "11", label: "快速时间录制" },
  { value: "12", label: "快速时间放大" },
  { value: "13", label: "设置高质量比例" },
  { value: "14", label: "视频0.5倍速 + 光流法补帧到60帧" },
  { value: "15", label: "裁切视频画面" },
  { value: "16", label: "视频旋转度数" },
  { value: "17", label: "水平翻转画面" },
  { value: "18", label: "垂直翻转画面" },
  { value: "19", label: "设定至指定分辨率并且自动填充黑边" },
  { value: "20", label: "转码到mp3" },
  { value: "21", label: "音频两倍速" },
  { value: "22", label: "音频倒放" },
  { value: "23", label: "声音响度标准化" },
  { value: "24", label: "音量大小调节" },
  { value: "25", label: "静音第一个声道" },
  { value: "26", label: "静音所有声道" },
  { value: "27", label: "交换左右声道" },
  { value: "28", label: "gif(15fps,480p)" },
  { value: "29", label: "从视频区间每秒提取n张照片" },
  { value: "30", label: "截取指定数量的帧保存为图片" },
  { value: "31", label: "视频或音乐添加封面图片" },
];

const audioOptions2 = [
  { value: "32", label: "转码到mp3" },
  { value: "33", label: "音频两倍速" },
  { value: "34", label: "音频倒放" },
  { value: "35", label: "声音响度标准化" },
  { value: "36", label: "音量大小调节" },
  { value: "37", label: "静音第一个声道" },
  { value: "38", label: "静音所有声道" },
  { value: "39", label: "交换左右声道" },
];

const picOptions2 = [
  { value: "40", label: "JPEG压缩质量(1-31,越大压缩率越高)" },
  { value: "41", label: "PNG无损压缩(zlib 1-9)" },
  { value: "42", label: "WebP压缩(质量0-100)" },
];

const options = [
  {
    value:
      "*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.m4v *.mpg *.mpeg *.vob *.ogv *.mxf *.ts *.m2ts *.divx *.3gp *.asf *.rm *.rmvb",
    label:
      "*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.m4v *.mpg *.mpeg *.vob *.ogv *.mxf *.ts *.m2ts *.divx *.3gp *.asf *.rm *.rmvb",
  },
  {
    value:
      "*.mp3 *.wav *.aac *.flac *.m4a *.wma *.ogg *.ac3 *.aiff *.alac *.ape *.opus *.ra *.wv *.mka *.dts *.mpc",
    label:
      "*.mp3 *.wav *.aac *.flac *.m4a *.wma *.ogg *.ac3 *.aiff *.alac *.ape *.opus *.ra *.wv *.mka *.dts *.mpc",
  },
  {
    value:
      "*.jpg *.jpeg *.png *.gif *.bmp *.tiff *.webp *.tga *.dpx *.exr *.pam *.pbm *.pcx *.pgm *.ppm *.sgi *.xwd *.heic",
    label:
      "*.jpg *.jpeg *.png *.gif *.bmp *.tiff *.webp *.tga *.dpx *.exr *.pam *.pbm *.pcx *.pgm *.ppm *.sgi *.xwd *.heic",
  },
];

const App = () => {
  const [activeTab, setActiveTab] = useState("convert");
  const [value, setValue] = useState("");
  const [value2, setValue2] = useState("");
  const [form, setForm] = useState({
    inputType: "",
    inputDirectory: "",
    inputFile: "",
    outputDirectory: "",
    outputChecked: false,
  });
  const [commandForm, setCommandForm] = useState({
    ffmpegOptions: "",
    ffmpegCommands: "",
    ffmpegLog: "",
  });

  useEffect(() => {
    const unlisten = listen("ffmpeg_log", (event) => {
      setCommandForm((prevState) => ({
        ...prevState,
        ffmpegLog: prevState.ffmpegLog + event.payload,
      }));
    });

    return () => {
      unlisten.then((f) => f());
    };
  }, []);

  const logRef = useRef(null);
  useEffect(() => {
    if (logRef.current) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [commandForm.ffmpegLog]);

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const handleFormatChange = (event) => {
    setValue(event.target.value);
    setValue2(""); // 清空操作方式选择
  };

  const selectDirectory = async () => {
    const selected = await open({
      directory: true,
      multiple: false,
    });
    if (selected) {
      setForm({ ...form, inputDirectory: selected, inputType: "1" });
    }
  };

  const selectOutputDirectory = async () => {
    const selected = await open({
      directory: true,
      multiple: false,
    });
    if (selected) {
      setForm({ ...form, outputDirectory: selected, outputChecked: true });
    }
  };

  const selectFile = async () => {
    const selected = await open({
      directory: false,
      multiple: false,
    });
    if (selected) {
      setForm({ ...form, inputFile: selected, inputType: "2" });
    }
  };

  const onSubmit = async () => {
    console.log("Submit!", form, commandForm);
    const inputPath = form.inputType === "1" ? form.inputDirectory : form.inputFile;
    const outputPath = form.outputDirectory;
    const options = commandForm.ffmpegOptions;
    const supportedFormats = value; // 添加支持格式参数

    try {
      const log = await invoke(
        form.inputType === "1" ? "run_ffmpeg_batch" : "run_ffmpeg",
        { inputPath, outputPath, options, supportedFormats }
      );
      setCommandForm({ ...commandForm, ffmpegLog: log });
    } catch (error) {
      console.error("Error running ffmpeg:", error);
      setCommandForm({ ...commandForm, ffmpegLog: error.toString() });
    }
  };

  const handleOperationChange2 = (value) => {
    const selectedValue = value;
    setValue2(selectedValue);
  }

  const handleOperationChange = (event) => {
    const selectedValue = event.target.value;
    // setValue2(selectedValue);

    let inputPath = form.inputType === "1" ? form.inputDirectory : form.inputFile;
    let outputPath = form.outputDirectory;
    let outputOptions = "";
    let ffmpegCommand = "";

    switch (selectedValue) {
      case "1":
        outputOptions = "-c copy";
        break;
      case "2":
        outputOptions = "-movflags faststart -acodec copy -vcodec copy";
        break;
      case "3":
        outputOptions = "-c:v libx264 -crf 23";
        break;
      case "4":
        outputOptions = "-c:v h264_vaapi -qp 23";
        break;
      case "5":
        outputOptions = "-c:v h264_amf -qp 23";
        break;
      case "6":
        outputOptions = "-c:v h264_nvenc -qp 23";
        break;
      case "7":
        outputOptions = "-c:v libx265 -crf 28 -preset medium";
        break;
      case "8":
        outputOptions = "-c:v hevc_amf -qp 28";
        break;
      case "9":
        outputOptions = "-c:v hevc_amf -qp 28";
        break;
      case "10":
        outputOptions = "-c:v hevc_nvenc -qp 28";
        break;
      case "11":
        outputOptions = "-vf setpts=0.5*PTS";
        break;
      case "12":
        outputOptions = "-vf setpts=2.0*PTS";
        break;
      case "13":
        outputOptions = "-vf scale=iw*0.5:ih*0.5";
        break;
      case "14":
        outputOptions = "-vf minterpolate=fps=60";
        break;
      case "15":
        outputOptions = "-vf crop=iw/2:ih/2:0:0";
        break;
      case "16":
        outputOptions = "-vf transpose=1";
        break;
      case "17":
        outputOptions = "-vf hflip";
        break;
      case "18":
        outputOptions = "-vf vflip";
        break;
      case "19":
        outputOptions = "-vf scale=1280:720,pad=iw:ih:(ow-iw)/2:(oh-ih)/2";
        break;
      case "20":
        outputOptions = "-c:a libmp3lame -q:a 2";
        break;
      case "21":
        outputOptions = "-filter:a atempo=2.0";
        break;
      case "22":
        outputOptions = "-filter:a areverse";
        break;
      case "23":
        outputOptions = "-filter:a loudnorm";
        break;
      case "24":
        outputOptions = "-filter:a volume=0.5";
        break;
      case "25":
        outputOptions = "-filter:a pan=mono|c0=c0";
        break;
      case "26":
        outputOptions = "-filter:a volume=0";
        break;
      case "27":
        outputOptions = "-filter:a stereotools=swapsides";
        break;
      case "28":
        outputOptions = "-vf fps=15,scale=480:-1";
        break;
      case "29":
        outputOptions = "-vf fps=1,scale=480:-1";
        break;
      case "30":
        outputOptions = "-vf select=not(mod(n\,100))";
        break;
      case "31":
        outputOptions = "-i cover.jpg -map 0 -map 1 -c copy -c:v:1 png -disposition:v:1 attached_pic";
        break;
      case "32":
        outputOptions = "-c:a libmp3lame -q:a 2";
        break;
      case "33":
        outputOptions = "-filter:a \"atempo=2.0\"";
        break;
      case "34":
        outputOptions = "-af areverse";
        break;
      case "35":
        outputOptions = "-filter:a loudnorm";
        break;
      case "36":
        outputOptions = "-filter:a volume=2.0";
        break;
      case "37":
        outputOptions = "-af \"pan=stereo|c0=c0|c1=0*c1\"";
        break;
      case "38":
        outputOptions = "-an";
        break;
      case "39":
        outputOptions = "-af \"pan=stereo|c0=c1|c1=c0\"";
        break;
      case "40":
        outputOptions = "-q:v 20";
        break;
      case "41":
        outputOptions = "-compression_level 9";
        break;
      case "42":
        outputOptions = "-quality 80";
        break;
      default:
        outputOptions = "";
    }

    ffmpegCommand = `ffmpeg -y -hide_banner -i "${inputPath}" ${outputOptions} "${outputPath}"`;

    setCommandForm({
      ...commandForm,
      ffmpegOptions: outputOptions,
      ffmpegCommands: ffmpegCommand,
    });
  };

  const filteredOptions2 = value.includes("*.mp3")
    ? audioOptions2
    : value.includes("*.jpg")
    ? picOptions2
    : options2;

  return (
    <Container
      style={{ height: "98vh", display: "flex", flexDirection: "column" }}
    >
      <Box style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <Tabs value={activeTab} onChange={handleTabChange} variant="fullWidth">
          <Tab label="转换" value="convert" />
          <Tab label="合并" value="merge" />
          <Tab label="分割" value="split" />
          <Tab label="设置" value="settings" />
          <Tab label="帮助" value="help" />
        </Tabs>
        {activeTab === "convert" && (
          <Box style={{ padding: "10px", flex: 1, display: "flex" }}>
            <Box style={{ flex: "0 0 70%", paddingRight: "20px" }}>
              <FormControl fullWidth style={{ marginTop: "10px" }} component="fieldset">
                <RadioGroup
                  row
                  value={form.inputType}
                  onChange={(e) =>
                    setForm({ ...form, inputType: e.target.value })
                  }
                >
                  <FormControlLabel
                    value="1"
                    control={<Radio />}
                    label="输入目录(批量):"
                  />
                  <TextField
                    value={form.inputDirectory}
                    onChange={(e) =>
                      setForm({ ...form, inputDirectory: e.target.value })
                    }
                    placeholder="请选择目录"
                    style={{ marginLeft: "10px", flex: 1 }}
                    size="small"
                    sx={{ width: "55ch" }}
                  />
                  <Button
                    onClick={selectDirectory}
                    style={{ marginLeft: "10px" }}
                  >
                    选择目录
                  </Button>
                </RadioGroup>
              </FormControl>

              <FormControl fullWidth component="fieldset" style={{ marginTop: "10px" }}>
                <RadioGroup
                  row
                  value={form.inputType}
                  onChange={(e) =>
                    setForm({ ...form, inputType: e.target.value })
                  }
                >
                  <FormControlLabel
                    value="2"
                    control={<Radio />}
                    label="输入文件(单文件):"
                  />
                  <TextField
                    value={form.inputFile}
                    onChange={(e) =>
                      setForm({ ...form, inputFile: e.target.value })
                    }
                    placeholder="请选择文件"
                    style={{ marginLeft: "10px", flex: 1 }}
                    size="small"
                    sx={{ width: "55ch" }}
                  />
                  <Button onClick={selectFile} style={{ marginLeft: "10px" }}>
                    选择文件
                  </Button>
                </RadioGroup>
              </FormControl>

              <FormControl fullWidth style={{ marginTop: "10px" }} component="fieldset">
                <Box display="flex"  alignItems="center">
                  <TextField id="outlined-basic" label="输出目录" variant="outlined"
                    value={form.outputDirectory}
                    onChange={(e) =>
                      setForm({ ...form, outputDirectory: e.target.value })
                    }
                    placeholder="输出目录"
                    style={{ marginLeft: "10px", flex: 1 }}
                    size="small"
                    sx={{ width: "55ch" }}
                  />
                  <Button
                    onClick={selectOutputDirectory}
                    style={{ marginLeft: "10px" }}
                  >
                    选择目录
                  </Button>
                </Box>
              </FormControl>

              <FormControl fullWidth style={{ marginTop: "10px" }} component="fieldset">
                <Box display="flex" alignItems="center">
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={form.outputChecked}
                        onChange={(e) =>
                          setForm({ ...form, outputChecked: e.target.checked })
                        }
                      />
                    }
                    label="输出扩展名:"
                  />
                  <TextField
                    value={form.outputDirectory}
                    onChange={(e) =>
                      setForm({ ...form, outputDirectory: e.target.value })
                    }
                    placeholder="示例扩展名: mp4"
                    style={{ marginLeft: "10px", flex: 1 }}
                    size="small"
                    sx={{ width: "55ch" }}
                  />
                </Box>
              </FormControl>

              <FormControl fullWidth style={{ marginTop: "10px" }} size="small">
                <InputLabel>支持格式</InputLabel>
                <Select
                  value={value}
                  id="demo-select-small"
                  onChange={handleFormatChange}
                  fullWidth
                  label="支持格式"
                >
                  {options.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>

              <Typography variant="h8" style={{ marginTop: "10px" }}>
                输出选项:
              </Typography>
              <TextField
                multiline
                rows={3}
                value={commandForm.ffmpegOptions}
                onChange={(e) =>
                  setCommandForm({
                    ...commandForm,
                    ffmpegOptions: e.target.value,
                  })
                }
                placeholder="输出选项"
                fullWidth
                style={{ marginTop: "10px" }}
                size="small"
              />
            </Box>

            <Box style={{ flex: "0 0 30%", borderLeft: "1px solid #ddd", paddingLeft: "20px" }}>
              <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
                <Tabs value={value2} aria-label="操作方式标签页">
                  <Tab label="视频" value="1" onClick={() => handleOperationChange2("1")}/>
                  <Tab label="音频" value="2" onClick={() => handleOperationChange2("2")}/>
                  <Tab label="图片" value="3" onClick={() => handleOperationChange2("3")}/>
                </Tabs>
              </Box>
              <Box sx={{ maxHeight: "calc(100vh - 500px)", overflowY: "auto" }}>
                {(value2 === "1" || !value2) && (
                  <Box>
                    {options2.slice(0, 19).map((option) => (
                      <MenuItem key={option.value} value={option.value} onClick={() => handleOperationChange({ target: { value: option.value } })}>
                        {option.label}
                      </MenuItem>
                    ))}
                  </Box>
                )}
                {value2 === "2" && (
                  <Box>
                    {audioOptions2.map((option) => (
                      <MenuItem key={option.value} value={option.value} onClick={() => handleOperationChange({ target: { value: option.value } })}>
                        {option.label}
                      </MenuItem>
                    ))}
                  </Box>
                )}
                {value2 === "3" && (
                  <Box>
                    {picOptions2.map((option) => (
                      <MenuItem key={option.value} value={option.value} onClick={() => handleOperationChange({ target: { value: option.value } })}>
                        {option.label}
                      </MenuItem>
                    ))}
                  </Box>
                )}
              </Box>
            </Box>
          </Box>
        )}
        {activeTab === "merge" && <p>合并功能的内容</p>}
        {activeTab === "split" && <p>分割功能的内容</p>}
        {activeTab === "settings" && <p>设置功能的内容</p>}
        {activeTab === "help" && <p>帮助功能的内容</p>}

        
        <Typography variant="h8" style={{ marginTop: "10px" }}>
          FFmpeg命令:
        </Typography>
        <TextField
          multiline
          rows={4}
          value={commandForm.ffmpegCommands}
          onChange={(e) =>
            setCommandForm({
              ...commandForm,
              ffmpegCommands: e.target.value,
            })
          }
          placeholder="FFmpeg命令"
          fullWidth
          style={{ marginTop: "10px" }}
          size="small"
        />
        <Typography variant="h8" style={{ marginTop: "10px" }}>
          FFmpeg日志:
        </Typography>
        <TextField
          multiline
          rows={5}
          value={commandForm.ffmpegLog}
          onChange={(e) =>
            setCommandForm({ ...commandForm, ffmpegLog: e.target.value })
          }
          placeholder="FFmpeg日志"
          fullWidth
          style={{ marginTop: "10px" }}
          size="small"
          inputRef={logRef}
        />
        <Button
          variant="contained"
          color="primary"
          onClick={onSubmit}
          style={{ marginTop: "20px", alignSelf: "center" }}
          fullWidth
        >
          开始转换
        </Button>
      </Box>
    </Container>
  );
};

export default App;
